<?php

namespace Upsanddowns\Controller;
use Think\Controller;

/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class BaseController extends Controller {

	private $appid;		//公众号id
	private $secret;	//公众号密匙
	private $token;		//公众号token
	private $public_config;	//公众号配置信息
	/**
	 * [_empty 空操作，用于输出404页面]
	 * @return [type] [description]
	 */
	public function _empty(){
		$this->redirect('Index/index');
	}
	
	/**
	 * [init_public 初始化公招信息]
	 * @return [type] [description]
	 */
	private function init_public(){
		//约定该系统所使用的公众号始终是uid为1的(admin)账号的当前使用的公众号信息
		//获取公众号id
		$where = array();
		$where['uid'] = 1;
		$where['is_use'] = 1;
		$where['is_creator'] =1;
		$mp_id = M('MemberPublicLink')->where($where)->getField('mp_id');
		//获取公众号信息
		$public = M('MemberPublic')->field('token,appid,secret,addon_config')->find($mp_id);
		//初始化赋值
		$this->appid = $public['appid'];
		$this->secret = $public['secret'];
		$this->token = $public['token'];

		$config = json_decode($public['addon_config'],true);
		$config = $config['Leaflets'];
		$config ['img'] = is_numeric ( $config ['img'] ) ? get_cover_url ( $config ['img'] ) :'';
		$this->public_config = $config;
	}
	
	/**
	 * [_initialize 任何控制器之前的初始化操作，主要用于微信登录]
	 * @return [type] [description]
	 */
	function _initialize() {
		$this->init_public();
		$user['openid']='wx0a6eff070a1eaf63';
		$user['uid']='d410';
		$user = cookie('user_auth');
		$openid = $user['openid'];
		//判断用户openid是否存在
		if(!$user['openid'] || empty($user['uid'])){
			//如果不存在则重新获取openid并且保存进session
			$state=str_replace("&","△",$_SERVER['REQUEST_URI']);
			$redirect_uri="http://" . $_SERVER['HTTP_HOST'] ."/upsanddowns.php?s=/Index/weixin_call_back";
			$appid = $this->appid;
			$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".urlencode($redirect_uri)."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect";
			header("location:".$url."");
		}else{
			$res = M ( 'Follow' )->field('id,headimgurl,login_time,subscribe')->where(array('openid'=>$openid,'status'=>1))->find();
		    //每天首次登录送1000金豆
	        if(date('Ymd',$res['login_time'])!=date('Ymd')){
	            $data['login_time']=time();
	            if(M('Follow')-> where('id='.$res['id'])->setField($data)){
	                $other=array('user_id'=>$res['id'],'type'=>3,'log_info'=>'每天用户登录送1000金豆');
	                //减少用户帐户中的金豆并记录日志
	                modify_account(array('gold_bean'=>1000),$other);
	            }
	        }
	        $headimgurl = $res['headimgurl'];
	        $this->assign('headimgurl',$headimgurl);
			if($res['subscribe']!=1){
				if(!empty($this->public_config)){
					$this->assign('public_config',$this->public_config);
				}
				$info = $this->getWeixinUserInfo($openid);
				$res = D ( 'Common/Follow' )->where (array('openid'=>$openid,'statuu'=>1) )->save ( $info );
			}
				
		}
		
	}

	/**
	 * [weixin 授权登录回调函数]
	 * @return [type] [description]
	 */
	public function weixin_call_back(){
		//获取回调参数
		$code=$_GET['code'];
		$state=$_GET['state'];
		if($code){
			//APPID 和 APPSERET 替换成为变量 TODO
			$appid = $this->appid;
			$appsecret = $this->secret;
			$back_openid_arr=$this->get_openid($appid,$appsecret,$code);
			$openid = $back_openid_arr['openid'];
			$user['openid'] = $openid;
			
			$userinfo = M ( 'Follow' )->field('id,nickname,openid,status,subscribe_time,login_time')->where(array('openid'=>$openid))->find();
			if(!empty($openid) && !$userinfo){
				$userinfo['token'] = $this->token;
				$info = D ( 'Common/Follow' )->init_follow ( $openid,$userinfo);
				$other=array('user_id'=>$info['id'],'type'=>3,'log_info'=>'用户首次注册送10000金豆');
				//减少用户帐户中的金豆并记录日志
				if($info){
					$user['uid'] = $info['id'];
					modify_account(array('gold_bean'=>10000),$other);
				}
                
			}else{
				$user['uid'] = $userinfo['id'];
				$user['nickname'] = $userinfo['nickname'];
				if(empty($userinfo['nickname']) || (time()>$userinfo['login_time']+86400)){ //没有写入详细信息 或者更新时间超过24小时
					$info = $this->getWeixinUserInfo($openid);
                    $res = D ( 'Common/Follow' )->where ( array('openid'=>$openid) )->save ( $info );
				}         
			}
			
			cookie('user_auth',$user);
			header("location:http://".$_SERVER['HTTP_HOST'].str_replace("△","&",$state));
		}else{
			echo "未授权";
			exit;
		}
	}

	/**
	 * [get_openid description]
	 * @param  [type] $appid     [公众号ID]
	 * @param  [type] $appsecret [公众号密匙]
	 * @param  [type] $code      [回调GET参数]
	 * @return [type]            [openid]
	 */
	function get_openid($appid,$appsecret,$code){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code");
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		if(curl_errno($ch)){
			return curl_error($ch);
		}
		curl_close($ch);
		return json_decode($tmpInfo,true);

	}

	/**
	 * [getWeixinUserInfo 通过openid获取微信用户基本信息,此功能只有认证的服务号才能用]
	 * @param  [type] $openid [description]
	 * @return [type]         [description]
	 */
	function getWeixinUserInfo($openid) {
		if (empty ( $GLOBALS ['user'] ['appid'] )) {
			//return false;
		}
		$appid = $this->appid;
		$appsecret = $this->secret;
		$param ['appid'] = $appid;
		$param ['secret'] = $appsecret;
		$param ['grant_type'] = 'client_credential';
		//token改为缓存获取 TODO
		$url = 'https://api.weixin.qq.com/cgi-bin/token?' . http_build_query ( $param );
		$content = file_get_contents ( $url );
		$content = json_decode ( $content, true );
		
		$param2 ['access_token'] = $content ['access_token'];
		$param2 ['openid'] = $openid;
		$param2 ['lang'] = 'zh_CN';
		
		$url = 'https://api.weixin.qq.com/cgi-bin/user/info?' . http_build_query ( $param2 );
		$content = file_get_contents ( $url );
		$content = json_decode ( $content, true );
		return $content;
	}



}
